# 系统控制模块 - 升级版本
import os
import subprocess
import sys
import platform
import time
import pyautogui
import psutil
import ctypes
import logging
import json
import traceback
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional, Tuple, List

# 首先配置日志系统
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("system_controller.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("SystemController")

# 尝试导入设置管理器
try:
    from settings_manager import (
        settings_manager,
        get_setting,
        set_setting,
        get_context,
        add_to_context,
        clear_context,
        get_error_suggestion,
        get_voice_params
    )
    SETTINGS_AVAILABLE = True
    logger.info("设置管理器模块加载成功")
except ImportError:
    SETTINGS_AVAILABLE = False
    logging.warning("设置管理器模块未找到，用户体验优化功能将不可用")
except Exception as e:
    SETTINGS_AVAILABLE = False
    logging.error(f"加载设置管理器模块失败: {str(e)}")

# 尝试导入屏幕内容理解模块 (CR模块)
CR_MODULE_AVAILABLE = False
OCR_AVAILABLE = False
try:
    # 先确认文件是否存在
    module_path = os.path.join(os.path.dirname(__file__), 'cr_module.py')
    if os.path.exists(module_path):
        import cr_module
        CR_MODULE_AVAILABLE = True
        logger.info("屏幕内容理解模块加载成功")
        # 初始化CR模块
        try:
            if hasattr(cr_module, 'initialize'):
                CR_MODULE_AVAILABLE = cr_module.initialize()
                if CR_MODULE_AVAILABLE:
                    logger.info("屏幕内容理解模块初始化成功")
                else:
                    logger.warning("屏幕内容理解模块初始化不完全，可能需要安装Tesseract OCR")
            else:
                # 检查模块可用性
                if hasattr(cr_module, 'is_available'):
                    CR_MODULE_AVAILABLE = cr_module.is_available()
        except Exception as init_error:
            logger.error(f"初始化屏幕内容理解模块时出错: {str(init_error)}")
            CR_MODULE_AVAILABLE = False
        
        OCR_AVAILABLE = CR_MODULE_AVAILABLE
    else:
        logger.warning(f"CR模块文件不存在: {module_path}")
except ImportError as e:
    logger.error(f"导入CR模块失败: {str(e)}")
    # 尝试回退到OCR模块
    try:
        from ocr_module import initialize_ocr_module
        OCR_AVAILABLE = True
        logger.info("OCR模块加载成功")
    except ImportError:
        logger.warning("CR模块未找到，屏幕内容理解功能将不可用")
except Exception as e:
    logger.error(f"加载屏幕内容理解模块失败: {str(e)}")
    CR_MODULE_AVAILABLE = False

# 尝试导入工作流管理模块
WORKFLOW_AVAILABLE = False
try:
    # 先确认文件是否存在
    module_path = os.path.join(os.path.dirname(__file__), 'workflow_manager.py')
    if os.path.exists(module_path):
        import workflow_manager
        WORKFLOW_AVAILABLE = True
        logger.info("工作流管理模块加载成功")
        # 初始化工作流管理器
        try:
            if hasattr(workflow_manager, 'initialize'):
                workflow_manager.initialize()
                logger.info("工作流管理模块初始化成功")
            else:
                # 如果没有initialize方法，创建全局实例
                if not hasattr(workflow_manager, 'workflow_manager'):
                    # 动态导入WorkflowManager类
                    WorkflowManager = getattr(workflow_manager, 'WorkflowManager', None)
                    if WorkflowManager:
                        workflow_manager.workflow_manager = WorkflowManager()
                        logger.info("工作流管理模块实例创建成功")
                    else:
                        logger.warning("无法找到WorkflowManager类")
        except Exception as init_error:
            logger.error(f"初始化工作流管理模块时出错: {str(init_error)}")
            WORKFLOW_AVAILABLE = False
    else:
        logger.warning(f"工作流管理模块文件不存在: {module_path}")
except ImportError as e:
    logger.error(f"导入工作流管理模块失败: {str(e)}")
    logger.warning("工作流管理模块未找到，自动化工作流功能将不可用")
except Exception as e:
    logger.error(f"加载工作流管理模块失败: {str(e)}")
    WORKFLOW_AVAILABLE = False

# 尝试导入大模型增强模块
try:
    from model_enhancer import initialize_model_manager, get_model_manager, ModelType
    MODEL_ENHANCER_AVAILABLE = True
    # 初始化模型管理器
    try:
        model_manager = initialize_model_manager()
        logger.info("大模型增强模块初始化成功")
    except Exception as e:
        logger.error(f"初始化大模型管理器失败: {str(e)}")
except ImportError:
    MODEL_ENHANCER_AVAILABLE = False
    logging.warning("大模型增强模块未找到，模型增强功能将不可用")
except Exception as e:
    MODEL_ENHANCER_AVAILABLE = False
    logging.error(f"加载大模型增强模块失败: {str(e)}")

# 日志系统已在文件顶部配置

class CommandHandler(ABC):
    """命令处理器抽象基类"""
    
    def __init__(self, system_info: Dict[str, Any]):
        """初始化命令处理器
        
        Args:
            system_info: 系统信息字典
        """
        self.system_info = system_info
        self.current_os = system_info.get("os", "Unknown")
        self.user_id = "default"
    
    @abstractmethod
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行命令
        
        Args:
            parameters: 命令参数
            
        Returns:
            执行结果消息
        """
        pass
    
    def _validate_parameters(self, parameters: Dict[str, Any], required_params: list) -> tuple:
        """验证参数
        
        Args:
            parameters: 命令参数
            required_params: 必需参数列表
            
        Returns:
            (是否有效, 错误消息)
        """
        for param in required_params:
            if param not in parameters:
                return False, f"缺少必需参数: {param}"
        return True, ""
    
    def set_user_id(self, user_id: str) -> None:
        """设置用户ID，用于上下文管理"""
        self.user_id = user_id
    
    def _handle_error(self, error: Exception, command_name: str, retry_count: int = 0) -> str:
        """统一错误处理
        
        Args:
            error: 异常对象
            command_name: 命令名称
            retry_count: 当前重试次数
            
        Returns:
            错误处理后的响应消息
        """
        error_message = str(error)
        logger.error(f"命令执行错误 [{command_name}]: {error_message}\n{traceback.format_exc()}")
        
        # 添加到上下文历史
        if SETTINGS_AVAILABLE:
            add_to_context({
                "type": "error",
                "command": command_name,
                "error": error_message
            }, self.user_id)
        
        # 检查是否支持自动重试
        if SETTINGS_AVAILABLE and get_setting('error_handling.auto_retry', True):
            max_retries = get_setting('error_handling.max_retries', 2)
            if retry_count < max_retries:
                retry_delay = get_setting('error_handling.retry_delay', 1.0)
                logger.info(f"将在 {retry_delay} 秒后重试命令，剩余次数: {max_retries - retry_count}")
                time.sleep(retry_delay)
                return self.execute({**parameters, "_retry_count": retry_count + 1})
        
        # 生成错误响应
        response = f"❌ 命令执行失败: {error_message}"
        
        # 添加错误建议
        if SETTINGS_AVAILABLE and get_setting('error_handling.show_suggestions', True):
            suggestion = get_error_suggestion(error_message, command_name)
            response += f"\n💡 {suggestion}"
        
        return response

class ApplicationCommandHandler(CommandHandler):
    """应用程序命令处理器"""
    
    def __init__(self, system_info: Dict[str, Any]):
        super().__init__(system_info)
        self.app_paths = {
            "chrome": "C:\Program Files\Google\Chrome\Application\chrome.exe",
            "edge": "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
            "firefox": "C:\Program Files\Mozilla Firefox\firefox.exe",
            "word": "C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE",
            "excel": "C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE",
            "notepad": "notepad.exe",
            "calculator": "calc.exe",
            "cmd": "cmd.exe",
            "powershell": "powershell.exe",
            "记事本": "notepad.exe",
            "命令提示符": "cmd.exe",
            "命令行": "cmd.exe",
            "终端": "cmd.exe",
            "画图": "mspaint.exe",
            "资源管理器": "explorer.exe"
        }
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行应用程序相关命令"""
        command_type = parameters.get("type", "")
        
        if command_type == "open":
            return self._open_application(parameters)
        elif command_type == "close":
            return self._close_application(parameters)
        elif command_type == "close_window":
            return self._close_window()
        else:
            return f"未知的应用命令类型: {command_type}"
    
    def _open_application(self, parameters: Dict[str, Any]) -> str:
        """启动应用程序"""
        app_name = parameters.get("app_name", "")
        if not app_name:
            return "启动应用程序失败，请提供应用程序名称"
        
        try:
            # 转换应用名称为小写进行匹配
            app_name_lower = app_name.lower()
            
            # 检查是否有预定义路径
            for key, path in self.app_paths.items():
                if key.lower() in app_name_lower or app_name_lower in key.lower():
                    if os.path.exists(path):
                        subprocess.Popen(path)
                        logger.info(f"成功启动应用: {app_name} (路径: {path})")
                        return f"成功启动{app_name}"
                    
            # 尝试使用系统默认方式打开
            if self.current_os == "Windows":
                try:
                    os.startfile(app_name_lower)
                    logger.info(f"使用系统默认方式启动应用: {app_name}")
                    return f"成功启动{app_name}"
                except FileNotFoundError:
                    # 尝试直接运行
                    subprocess.Popen([app_name_lower])
                    logger.info(f"尝试直接运行应用: {app_name}")
                    return f"尝试打开{app_name}"
            elif self.current_os == "Darwin":  # macOS
                subprocess.Popen(["open", "-a", app_name_lower])
                logger.info(f"在macOS上启动应用: {app_name}")
                return f"成功启动{app_name}"
            else:  # Linux
                subprocess.Popen(["xdg-open", app_name_lower])
                logger.info(f"在Linux上启动应用: {app_name}")
                return f"成功启动{app_name}"
        except Exception as e:
            logger.error(f"启动应用失败: {str(e)}")
            return f"无法启动{app_name}: {str(e)}"
    
    def _close_application(self, parameters: Dict[str, Any]) -> str:
        """关闭应用程序"""
        app_name = parameters.get("app_name", "")
        if not app_name:
            return "请提供要关闭的应用程序名称"
        
        try:
            if self.current_os == "Windows":
                # 对于Windows，尝试多种可能的进程名
                app_name_lower = app_name.lower()
                # 检查预定义的应用映射
                for key, path in self.app_paths.items():
                    if key.lower() in app_name_lower:
                        exe_name = os.path.basename(path)
                        subprocess.run(["taskkill", "/F", "/IM", exe_name], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                        logger.info(f"关闭应用: {app_name} (进程: {exe_name})")
                        return f"正在关闭{app_name}"
                # 尝试直接使用提供的名称
                subprocess.run(["taskkill", "/F", "/IM", f"{app_name}.exe"],
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                logger.info(f"尝试关闭应用: {app_name}")
                return f"正在关闭{app_name}"
            else:
                # macOS和Linux
                subprocess.run(["pkill", app_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                logger.info(f"在{self.current_os}上关闭应用: {app_name}")
                return f"正在关闭{app_name}"
        except Exception as e:
            logger.error(f"关闭应用失败: {str(e)}")
            return f"关闭应用时出错: {str(e)}"
    
    def _close_window(self) -> str:
        """关闭当前活动窗口"""
        try:
            pyautogui.hotkey('alt', 'f4')
            logger.info("关闭当前活动窗口")
            return "正在关闭当前窗口"
        except Exception as e:
            logger.error(f"关闭窗口失败: {str(e)}")
            return f"关闭窗口时出错: {str(e)}"

class FileCommandHandler(CommandHandler):
    """文件命令处理器"""
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行文件相关命令"""
        command_type = parameters.get("type", "")
        
        if command_type == "list":
            return self._list_files(parameters)
        elif command_type == "search":
            return self._search_files(parameters)
        elif command_type == "create_folder":
            return self._create_folder(parameters)
        elif command_type == "edit":
            return self._edit_file(parameters)
        elif command_type == "copy":
            return self._copy_file(parameters)
        elif command_type == "move":
            return self._move_file(parameters)
        elif command_type == "delete":
            return self._delete_file(parameters)
        else:
            return f"未知的文件命令类型: {command_type}"
    
    def _list_files(self, parameters: Dict[str, Any]) -> str:
        """列出文件和文件夹"""
        path = parameters.get("path", ".")
        
        try:
            # 验证路径是否存在
            if not os.path.exists(path):
                return f"路径不存在: {path}"
            
            files = os.listdir(path)
            if not files:
                return f"目录 {path} 为空"
            
            # 分类文件和文件夹
            folders = []
            regular_files = []
            
            for item in files:
                item_path = os.path.join(path, item)
                if os.path.isdir(item_path):
                    folders.append(f"📁 {item}")
                else:
                    try:
                        size = os.path.getsize(item_path) / 1024  # KB
                        size_str = f" ({size:.1f}KB)" if size < 1024 else f" ({size/1024:.1f}MB)"
                        regular_files.append(f"📄 {item}{size_str}")
                    except (OSError, PermissionError):
                        regular_files.append(f"📄 {item} (无法获取大小)")
            
            # 构建响应
            response = f"目录 {path} 的内容:\n"
            if folders:
                response += "\n文件夹:\n"
                response += "\n".join([f"  - {folder}" for folder in sorted(folders)])
            if regular_files:
                response += "\n\n文件:\n"
                response += "\n".join([f"  - {file}" for file in sorted(regular_files)[:10]])  # 限制显示数量
                if len(regular_files) > 10:
                    response += f"\n  - ...等{len(regular_files) - 10}个文件"
            
            logger.info(f"列出目录 {path} 的内容成功")
            return response
        except PermissionError:
            logger.error(f"没有权限访问目录: {path}")
            return f"没有权限访问目录: {path}"
        except Exception as e:
            logger.error(f"列出文件失败: {str(e)}")
            return f"列出文件失败: {str(e)}"
    
    def _search_files(self, parameters: Dict[str, Any]) -> str:
        """搜索文件"""
        keyword = parameters.get("keyword", "")
        path = parameters.get("path", ".")
        
        if not keyword:
            return "请提供搜索关键字"
        
        try:
            # 验证路径是否存在
            if not os.path.exists(path):
                return f"路径不存在: {path}"
            
            results = []
            max_results = 20
            search_depth = 3
            
            # 改进的文件搜索，带深度限制
            for root, dirs, files in os.walk(path):
                # 限制搜索深度
                current_depth = root[len(path):].count(os.sep)
                if current_depth > search_depth:
                    continue
                
                for file in files:
                    if keyword.lower() in file.lower():
                        full_path = os.path.join(root, file)
                        relative_path = os.path.relpath(full_path, path)
                        try:
                            size = os.path.getsize(full_path) / 1024  # KB
                            size_str = f" ({size:.1f}KB)" if size < 1024 else f" ({size/1024:.1f}MB)"
                            results.append(f"📄 {relative_path}{size_str}")
                        except (OSError, PermissionError):
                            results.append(f"📄 {relative_path} (无法获取大小)")
                        
                        if len(results) >= max_results:
                            break
                
                # 也搜索文件夹名称
                for dir in dirs:
                    if keyword.lower() in dir.lower():
                        full_path = os.path.join(root, dir)
                        relative_path = os.path.relpath(full_path, path)
                        results.append(f"📁 {relative_path}")
                        
                        if len(results) >= max_results:
                            break
                
                if len(results) >= max_results:
                    break
            
            if not results:
                return f"未找到包含'{keyword}'的文件或文件夹"
            
            response = f"找到{len(results)}个结果:\n"
            for result in results:
                response += f"  - {result}\n"
            
            logger.info(f"搜索关键字 '{keyword}' 成功，找到 {len(results)} 个匹配项")
            return response
        except PermissionError:
            logger.error(f"没有权限访问路径: {path}")
            return f"没有权限访问路径: {path}"
        except Exception as e:
            logger.error(f"搜索文件失败: {str(e)}")
            return f"搜索文件失败: {str(e)}"
    
    def _create_folder(self, parameters: Dict[str, Any]) -> str:
        """创建文件夹"""
        folder_name = parameters.get("folder_name", "新建文件夹")
        path = parameters.get("path", ".")
        
        if not folder_name:
            return "请提供文件夹名称"
        
        try:
            # 确保基础路径存在
            if not os.path.exists(path):
                os.makedirs(path)
                logger.info(f"创建基础路径: {path}")
            
            # 创建新文件夹
            full_path = os.path.join(path, folder_name)
            os.makedirs(full_path, exist_ok=True)
            
            logger.info(f"成功创建文件夹: {full_path}")
            return f"成功创建文件夹: {folder_name}"
        except PermissionError:
            logger.error(f"没有权限创建文件夹: {os.path.join(path, folder_name)}")
            return f"没有权限创建文件夹"
        except OSError as e:
            logger.error(f"创建文件夹失败: {str(e)}")
            return f"创建文件夹失败: {str(e)}"
    
    def _edit_file(self, parameters: Dict[str, Any]) -> str:
        """编辑文件内容"""
        try:
            file_path = parameters.get("path")
            content = parameters.get("content", "")
            append = parameters.get("append", False)
            
            if not file_path:
                return "请提供要编辑的文件路径"
            
            # 转换为绝对路径
            if not os.path.isabs(file_path):
                file_path = os.path.abspath(file_path)
            
            # 检查文件是否存在（非追加模式下）
            if not os.path.exists(file_path) and not append:
                # 询问是否创建新文件
                if not parameters.get("create_if_not_exists", False):
                    return f"文件 '{file_path}' 不存在，设置 create_if_not_exists=True 以创建新文件"
                
                # 确保目录存在
                os.makedirs(os.path.dirname(file_path), exist_ok=True)
            
            # 写入或追加内容
            mode = "a" if append else "w"
            with open(file_path, mode, encoding="utf-8") as f:
                f.write(content)
            
            action = "追加" if append else "写入"
            logger.info(f"成功{action}文件: {file_path}")
            return f"成功{action}文件: {file_path}\n写入内容长度: {len(content)} 字符"
        except PermissionError:
            logger.error(f"编辑文件权限不足: {str(file_path)}")
            return f"编辑文件失败: 权限不足，请检查您是否有足够权限编辑该文件"
        except Exception as e:
            logger.error(f"编辑文件失败: {str(e)}")
            return f"编辑文件失败: {str(e)}"
    
    def _copy_file(self, parameters: Dict[str, Any]) -> str:
        """复制文件或文件夹"""
        try:
            source_path = parameters.get("source")
            destination_path = parameters.get("destination")
            
            if not source_path or not destination_path:
                return "请提供源路径和目标路径"
            
            # 转换为绝对路径
            if not os.path.isabs(source_path):
                source_path = os.path.abspath(source_path)
            if not os.path.isabs(destination_path):
                destination_path = os.path.abspath(destination_path)
            
            # 检查源路径是否存在
            if not os.path.exists(source_path):
                return f"源路径 '{source_path}' 不存在"
            
            # 检查目标目录是否存在
            dest_dir = os.path.dirname(destination_path)
            if dest_dir and not os.path.exists(dest_dir):
                # 询问是否创建目标目录
                if not parameters.get("create_destination", False):
                    return f"目标目录 '{dest_dir}' 不存在，设置 create_destination=True 以创建目录"
                os.makedirs(dest_dir, exist_ok=True)
            
            # 复制文件
            import shutil
            if os.path.isfile(source_path):
                # 如果目标是目录，保持原文件名
                if os.path.isdir(destination_path):
                    filename = os.path.basename(source_path)
                    destination_path = os.path.join(destination_path, filename)
                
                # 检查目标文件是否存在
                if os.path.exists(destination_path) and not parameters.get("overwrite", False):
                    return f"目标文件 '{destination_path}' 已存在，设置 overwrite=True 以覆盖"
                
                shutil.copy2(source_path, destination_path)
                logger.info(f"成功复制文件: {source_path} -> {destination_path}")
                return f"成功复制文件: {source_path} -> {destination_path}"
            elif os.path.isdir(source_path):
                # 复制目录
                if os.path.exists(destination_path) and not parameters.get("overwrite", False):
                    return f"目标目录 '{destination_path}' 已存在，设置 overwrite=True 以覆盖"
                
                # 决定是否复制目录本身或仅复制内容
                if parameters.get("copy_content_only", False) and os.path.isdir(source_path):
                    # 仅复制内容
                    os.makedirs(destination_path, exist_ok=parameters.get("overwrite", False))
                    for item in os.listdir(source_path):
                        src_item = os.path.join(source_path, item)
                        dst_item = os.path.join(destination_path, item)
                        if os.path.isdir(src_item):
                            shutil.copytree(src_item, dst_item, dirs_exist_ok=parameters.get("overwrite", False))
                        else:
                            shutil.copy2(src_item, dst_item)
                    logger.info(f"成功复制目录内容: {source_path} -> {destination_path}")
                    return f"成功复制目录内容: {source_path} -> {destination_path}"
                else:
                    # 复制整个目录
                    shutil.copytree(source_path, destination_path, dirs_exist_ok=parameters.get("overwrite", False))
                    logger.info(f"成功复制目录: {source_path} -> {destination_path}")
                    return f"成功复制目录: {source_path} -> {destination_path}"
            else:
                return f"源路径 '{source_path}' 既不是文件也不是目录"
        except PermissionError:
            logger.error(f"复制文件权限不足: {str(source_path)} -> {str(destination_path)}")
            return f"复制文件失败: 权限不足，请检查您是否有足够权限进行复制操作"
        except Exception as e:
            logger.error(f"复制文件失败: {str(e)}")
            return f"复制文件失败: {str(e)}"
    
    def _move_file(self, parameters: Dict[str, Any]) -> str:
        """移动文件或文件夹"""
        try:
            source_path = parameters.get("source")
            destination_path = parameters.get("destination")
            
            if not source_path or not destination_path:
                return "请提供源路径和目标路径"
            
            # 转换为绝对路径
            if not os.path.isabs(source_path):
                source_path = os.path.abspath(source_path)
            if not os.path.isabs(destination_path):
                destination_path = os.path.abspath(destination_path)
            
            # 检查源路径是否存在
            if not os.path.exists(source_path):
                return f"源路径 '{source_path}' 不存在"
            
            # 检查目标目录是否存在
            dest_dir = os.path.dirname(destination_path)
            if dest_dir and not os.path.exists(dest_dir):
                # 询问是否创建目标目录
                if not parameters.get("create_destination", False):
                    return f"目标目录 '{dest_dir}' 不存在，设置 create_destination=True 以创建目录"
                os.makedirs(dest_dir, exist_ok=True)
            
            # 移动文件
            import shutil
            
            # 检查目标文件是否存在
            if os.path.exists(destination_path) and not parameters.get("overwrite", False):
                return f"目标 '{destination_path}' 已存在，设置 overwrite=True 以覆盖"
            
            # 如果目标是目录，保持原文件名
            if os.path.isdir(destination_path) and os.path.isfile(source_path):
                filename = os.path.basename(source_path)
                destination_path = os.path.join(destination_path, filename)
                
                # 再次检查新的目标路径
                if os.path.exists(destination_path) and not parameters.get("overwrite", False):
                    return f"目标文件 '{destination_path}' 已存在，设置 overwrite=True 以覆盖"
            
            # 如果目标文件已存在且允许覆盖，先删除它
            if os.path.exists(destination_path) and parameters.get("overwrite", False):
                if os.path.isdir(destination_path):
                    shutil.rmtree(destination_path)
                else:
                    os.remove(destination_path)
            
            shutil.move(source_path, destination_path)
            logger.info(f"成功移动: {source_path} -> {destination_path}")
            return f"成功移动: {source_path} -> {destination_path}"
        except PermissionError:
            logger.error(f"移动文件权限不足: {str(source_path)} -> {str(destination_path)}")
            return f"移动文件失败: 权限不足，请检查您是否有足够权限进行移动操作"
        except Exception as e:
            logger.error(f"移动文件失败: {str(e)}")
            return f"移动文件失败: {str(e)}"
    
    def _delete_file(self, parameters: Dict[str, Any]) -> str:
        """删除文件或文件夹"""
        try:
            file_path = parameters.get("path")
            
            if not file_path:
                return "请提供要删除的文件或文件夹路径"
            
            # 转换为绝对路径
            if not os.path.isabs(file_path):
                file_path = os.path.abspath(file_path)
            
            # 检查路径是否存在
            if not os.path.exists(file_path):
                return f"路径 '{file_path}' 不存在"
            
            # 安全检查
            if parameters.get("force", False) or self._confirm_delete(file_path, parameters):
                import shutil
                
                if os.path.isfile(file_path):
                    os.remove(file_path)
                    logger.info(f"成功删除文件: {file_path}")
                    return f"成功删除文件: {file_path}"
                elif os.path.isdir(file_path):
                    recursive = parameters.get("recursive", False)
                    if recursive:
                        shutil.rmtree(file_path)
                        logger.info(f"成功递归删除目录: {file_path}")
                        return f"成功递归删除目录: {file_path}"
                    else:
                        # 检查目录是否为空
                        if os.listdir(file_path):
                            return f"目录 '{file_path}' 不为空，请设置 recursive=True 以递归删除"
                        os.rmdir(file_path)
                        logger.info(f"成功删除空目录: {file_path}")
                        return f"成功删除空目录: {file_path}"
                else:
                    return f"路径 '{file_path}' 既不是文件也不是目录"
            else:
                return "删除操作已取消"
        except PermissionError:
            logger.error(f"删除权限不足: {str(file_path)}")
            return f"删除失败: 权限不足，请检查您是否有足够权限删除该文件或目录"
        except Exception as e:
            logger.error(f"删除失败: {str(e)}")
            return f"删除失败: {str(e)}"
    
    def _confirm_delete(self, file_path: str, parameters: Dict[str, Any]) -> bool:
        """确认删除操作"""
        # 在非交互模式下，需要明确的确认参数
        if not parameters.get("confirm", False):
            logger.warning(f"删除操作未经确认: {file_path}")
            return False
        
        # 检查是否为敏感目录
        sensitive_dirs = ["/", "C:", "D:", os.path.expanduser("~"), "C:\\Windows", "C:\\Program Files"]
        for sensitive_dir in sensitive_dirs:
            if file_path == sensitive_dir or file_path.startswith(sensitive_dir + os.sep):
                # 对于敏感目录，需要额外的安全确认
                if not parameters.get("confirm_sensitive", False):
                    logger.warning(f"尝试删除敏感目录: {file_path}")
                    return False
        
        return True

class SystemCommandHandler(CommandHandler):
    """系统命令处理器"""
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行系统相关命令"""
        command_type = parameters.get("type", "")
        
        if command_type == "info":
            return self._get_system_info()
        elif command_type == "shutdown":
            return self._shutdown(parameters)
        elif command_type == "restart":
            return self._restart(parameters)
        elif command_type == "sleep":
            return self._sleep()
        elif command_type == "monitor":
            return self._monitor_system_resources(parameters)
        else:
            return f"未知的系统命令类型: {command_type}"
    
    def _get_system_info(self) -> str:
        """获取系统信息"""
        try:
            # 获取CPU使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            cpu_count = psutil.cpu_count(logical=True)
            
            # 获取内存信息
            memory = psutil.virtual_memory()
            memory_used = round(memory.used / 1024 / 1024 / 1024, 2)
            memory_total = round(memory.total / 1024 / 1024 / 1024, 2)
            memory_percent = memory.percent
            
            # 获取磁盘信息
            disk = psutil.disk_usage('/')
            disk_used = round(disk.used / 1024 / 1024 / 1024, 2)
            disk_total = round(disk.total / 1024 / 1024 / 1024, 2)
            
            # 获取当前用户
            username = os.getlogin()
            
            # 系统信息
            system_info = platform.uname()
            
            info = f"""=== 系统信息 ===
用户名: {username}
操作系统: {system_info.system} {system_info.release}
处理器: {cpu_count}核 CPU使用率: {cpu_percent}%
内存: 总计 {memory_total:.2f}GB, 已用 {memory_used:.2f}GB ({memory_percent}%)
磁盘: 总计 {disk_total:.2f}GB, 已用 {disk_used:.2f}GB
Python版本: {sys.version}
计算机名: {system_info.node}
系统类型: {system_info.machine}"""
            
            logger.info("获取系统信息成功")
            return info
        except Exception as e:
            logger.error(f"获取系统信息失败: {str(e)}")
            return f"获取系统信息失败: {str(e)}"
    
    def _shutdown(self, parameters: Dict[str, Any]) -> str:
        """关闭计算机"""
        delay = parameters.get("delay", 30)
        confirm = parameters.get("confirm", False)
        
        if not confirm:
            return "关机命令需要确认，请添加confirm参数并设置为true"
        
        try:
            if self.current_os == "Windows":
                subprocess.run(["shutdown", "/s", "/t", str(delay)], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            elif self.current_os == "Darwin":
                minutes = delay // 60 if delay > 60 else 1
                subprocess.run(["shutdown", "-h", f"+{minutes}"], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            else:
                subprocess.run(["shutdown", "-h", f"+{delay // 60}"], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            
            logger.info(f"系统将在{delay}秒后关闭")
            return f"计算机将在{delay}秒后关闭"
        except Exception as e:
            logger.error(f"执行关机命令失败: {str(e)}")
            return f"执行关机命令失败: {str(e)}"
    
    def _restart(self, parameters: Dict[str, Any]) -> str:
        """重启计算机"""
        delay = parameters.get("delay", 30)
        confirm = parameters.get("confirm", False)
        
        if not confirm:
            return "重启命令需要确认，请添加confirm参数并设置为true"
        
        try:
            if self.current_os == "Windows":
                subprocess.run(["shutdown", "/r", "/t", str(delay)], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            elif self.current_os == "Darwin":
                minutes = delay // 60 if delay > 60 else 1
                subprocess.run(["shutdown", "-r", f"+{minutes}"], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            else:
                subprocess.run(["shutdown", "-r", f"+{delay // 60}"], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            
            logger.info(f"系统将在{delay}秒后重启")
            return f"计算机将在{delay}秒后重启"
        except Exception as e:
            logger.error(f"执行重启命令失败: {str(e)}")
            return f"执行重启命令失败: {str(e)}"
    
    def _sleep(self) -> str:
        """让计算机进入睡眠模式"""
        try:
            if self.current_os == "Windows":
                # Windows睡眠
                ctypes.windll.PowrProf.SetSuspendState(0, 1, 0)
            elif self.current_os == "Darwin":
                subprocess.run(["pmset", "sleepnow"], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            else:
                subprocess.run(["systemctl", "suspend"], 
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            
            logger.info("系统正在进入睡眠模式")
            return "计算机正在进入睡眠模式"
        except Exception as e:
            logger.error(f"执行睡眠命令失败: {str(e)}")
            return f"执行睡眠命令失败: {str(e)}"
    
    def _monitor_system_resources(self, parameters: Dict[str, Any]) -> str:
        """监控系统资源使用情况"""
        try:
            # 获取监控参数
            interval = parameters.get("interval", 1)  # 监控间隔（秒）
            duration = parameters.get("duration", 5)  # 监控持续时间（秒）
            threshold_cpu = parameters.get("threshold_cpu", 80)  # CPU使用率阈值（%）
            threshold_memory = parameters.get("threshold_memory", 80)  # 内存使用率阈值（%）
            threshold_disk = parameters.get("threshold_disk", 90)  # 磁盘使用率阈值（%）
            
            # 执行监控
            result = self._collect_system_metrics(interval, duration, 
                                               threshold_cpu, threshold_memory, threshold_disk)
            
            if result["has_warnings"]:
                response = "⚠️ 系统资源监控发现警告:\n\n"
                for warning in result["warnings"]:
                    response += f"- {warning}\n"
                response += "\n"
            else:
                response = "✅ 系统资源状态正常:\n\n"
            
            # 添加详细指标
            metrics = result["metrics"]
            response += f"平均CPU使用率: {metrics['avg_cpu']:.2f}%\n"
            response += f"平均内存使用率: {metrics['avg_memory']:.2f}%\n"
            response += f"磁盘使用率: {metrics['disk_usage']:.2f}%\n"
            response += f"活跃进程数: {metrics['process_count']}\n"
            response += f"系统温度: {metrics.get('temperature', '无法获取')}\n"
            
            # 添加建议
            if result["has_warnings"]:
                response += "\n建议操作:\n"
                if metrics['avg_cpu'] > threshold_cpu:
                    response += "- 关闭一些不必要的应用程序以降低CPU使用率\n"
                if metrics['avg_memory'] > threshold_memory:
                    response += "- 清理内存或关闭占用大量内存的应用\n"
                if metrics['disk_usage'] > threshold_disk:
                    response += "- 清理磁盘空间，删除不需要的文件\n"
            
            return response
        except Exception as e:
            logger.error(f"系统资源监控失败: {str(e)}")
            return f"系统资源监控失败: {str(e)}"
    
    def _collect_system_metrics(self, interval: int, duration: int, 
                               cpu_threshold: float, memory_threshold: float, 
                               disk_threshold: float) -> Dict[str, Any]:
        """收集系统指标"""
        start_time = time.time()
        end_time = start_time + duration
        
        cpu_usage_list = []
        memory_usage_list = []
        warnings = []
        
        # 获取磁盘信息
        disk_usage = psutil.disk_usage('/').percent
        
        # 监控循环
        while time.time() < end_time:
            # 获取CPU使用率
            cpu_usage = psutil.cpu_percent(interval=interval)
            cpu_usage_list.append(cpu_usage)
            
            # 获取内存使用率
            memory_info = psutil.virtual_memory()
            memory_usage_list.append(memory_info.percent)
            
            # 检查警告阈值
            if cpu_usage > cpu_threshold:
                warnings.append(f"CPU使用率过高: {cpu_usage:.2f}%")
            if memory_info.percent > memory_threshold:
                warnings.append(f"内存使用率过高: {memory_info.percent:.2f}%")
            if disk_usage > disk_threshold:
                warnings.append(f"磁盘使用率过高: {disk_usage:.2f}%")
        
        # 计算平均值
        avg_cpu = sum(cpu_usage_list) / len(cpu_usage_list) if cpu_usage_list else 0
        avg_memory = sum(memory_usage_list) / len(memory_usage_list) if memory_usage_list else 0
        
        # 获取活跃进程数
        process_count = len(psutil.pids())
        
        # 尝试获取CPU温度（在某些平台可能不可用）
        temperature = None
        try:
            if hasattr(psutil, 'sensors_temperatures'):
                temps = psutil.sensors_temperatures()
                if temps:
                    # 获取第一个温度传感器的数据作为参考
                    first_sensor = list(temps.values())[0]
                    temperature = f"{first_sensor[0].current:.1f}°C"
        except:
            pass
        
        return {
            "metrics": {
                "avg_cpu": avg_cpu,
                "avg_memory": avg_memory,
                "disk_usage": disk_usage,
                "process_count": process_count,
                "temperature": temperature
            },
            "warnings": list(set(warnings)),  # 去重
            "has_warnings": len(warnings) > 0
        }

class MediaCommandHandler(CommandHandler):
    """媒体控制命令处理器"""
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行媒体控制相关命令"""
        command_type = parameters.get("type", "")
        
        if command_type in ["increase", "decrease", "mute"]:
            return self._control_volume(command_type)
        elif command_type in ["brightness_up", "brightness_down"]:
            return self._control_brightness(command_type)
        elif command_type == "screenshot":
            return self._take_screenshot()
        elif command_type == "play_music":
            return self._play_music()
        else:
            return f"未知的媒体命令类型: {command_type}"
    
    def _control_volume(self, action: str) -> str:
        """控制音量"""
        try:
            if self.current_os == "Windows":
                # Windows音量控制
                if action == "increase":
                    for _ in range(5):
                        pyautogui.press('volumeup')
                elif action == "decrease":
                    for _ in range(5):
                        pyautogui.press('volumedown')
                elif action == "mute":
                    pyautogui.press('volumemute')
                
                logger.info(f"音量已{action}")
                return f"音量已{action}"
            else:
                # 尝试使用系统特定的音量控制方法
                if self.current_os == "Darwin":  # macOS
                    if action == "increase":
                        subprocess.run(["osascript", "-e", "set volume output volume (output volume of (get volume settings) + 10)"])
                    elif action == "decrease":
                        subprocess.run(["osascript", "-e", "set volume output volume (output volume of (get volume settings) - 10)"])
                    elif action == "mute":
                        subprocess.run(["osascript", "-e", "set volume output muted not (output muted of (get volume settings))"])
                    logger.info(f"在macOS上调整音量: {action}")
                    return f"音量已{action}"
                else:  # Linux
                    if action == "increase":
                        subprocess.run(["amixer", "-D", "pulse", "sset", "Master", "10%+"])
                    elif action == "decrease":
                        subprocess.run(["amixer", "-D", "pulse", "sset", "Master", "10%-"])
                    elif action == "mute":
                        subprocess.run(["amixer", "-D", "pulse", "sset", "Master", "toggle"])
                    logger.info(f"在Linux上调整音量: {action}")
                    return f"音量已{action}"
        except Exception as e:
            logger.error(f"控制音量失败: {str(e)}")
            return f"控制音量失败: {str(e)}"
    
    def _control_brightness(self, action: str) -> str:
        """控制屏幕亮度"""
        try:
            if self.current_os == "Windows":
                # Windows亮度控制
                if action == "brightness_up":
                    for _ in range(5):
                        pyautogui.press('brightnessup')
                elif action == "brightness_down":
                    for _ in range(5):
                        pyautogui.press('brightnessdown')
                
                logger.info(f"亮度已{action}")
                return f"亮度已{action}"
            elif self.current_os == "Darwin":  # macOS
                # 使用osascript控制亮度
                if action == "brightness_up":
                    subprocess.run(["osascript", "-e", "tell application \"System Events\" to key code 144"])
                elif action == "brightness_down":
                    subprocess.run(["osascript", "-e", "tell application \"System Events\" to key code 145"])
                logger.info(f"在macOS上调整亮度: {action}")
                return f"亮度已{action}"
            else:  # Linux
                # 尝试使用xbacklight控制亮度
                try:
                    if action == "brightness_up":
                        subprocess.run(["xbacklight", "-inc", "10"])
                    elif action == "brightness_down":
                        subprocess.run(["xbacklight", "-dec", "10"])
                    logger.info(f"在Linux上调整亮度: {action}")
                    return f"亮度已{action}"
                except FileNotFoundError:
                    return "Linux系统需要安装xbacklight工具来控制亮度"
        except Exception as e:
            logger.error(f"控制亮度失败: {str(e)}")
            return f"控制亮度失败: {str(e)}"
    
    def _take_screenshot(self) -> str:
        """截图"""
        try:
            # 创建截图目录
            screenshot_dir = "screenshots"
            os.makedirs(screenshot_dir, exist_ok=True)
            
            # 截图
            filename = os.path.join(screenshot_dir, f"screenshot_{time.strftime('%Y%m%d_%H%M%S')}.png")
            screenshot = pyautogui.screenshot()
            screenshot.save(filename)
            
            logger.info(f"截图成功，已保存到 {filename}")
            return f"截图成功，已保存到 {filename}"
        except ImportError:
            logger.error("需要安装pyautogui库来进行截图")
            return "需要安装pyautogui库来进行截图"
        except Exception as e:
            logger.error(f"截图失败: {str(e)}")
            return f"截图失败: {str(e)}"
    
    def _play_music(self) -> str:
        """播放音乐"""
        try:
            import webbrowser
            webbrowser.open("https://music.163.com/")
            logger.info("已打开网易云音乐")
            return "已打开网易云音乐"
        except Exception as e:
            logger.error(f"打开音乐播放器失败: {str(e)}")
            return f"打开音乐播放器失败: {str(e)}"

class OCRCommandHandler(CommandHandler):
    """OCR和屏幕内容理解命令处理器"""
    
    def __init__(self, system_info: Dict[str, Any]):
        super().__init__(system_info)
        self.ocr_processor = None
        self.screen_manager = None
        self.initialize_ocr_if_available()
    
    def initialize_ocr_if_available(self):
        """初始化OCR组件（如果可用）"""
        if OCR_AVAILABLE:
            try:
                self.ocr_processor, self.screen_manager = initialize_ocr_module()
                logger.info("OCR组件初始化成功")
            except Exception as e:
                logger.error(f"OCR组件初始化失败: {str(e)}")
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行OCR和屏幕内容理解相关命令"""
        if not OCR_AVAILABLE or not self.ocr_processor:
            return "OCR功能不可用，请确保已安装必要的依赖（pytesseract, PIL, opencv-python）"
        
        command_type = parameters.get("type", "")
        
        if command_type == "extract_text":
            return self._extract_text_from_screen(parameters)
        elif command_type == "find_text":
            return self._find_text_on_screen(parameters)
        elif command_type == "analyze_screen":
            return self._analyze_screen_content(parameters)
        elif command_type == "click_text":
            return self._click_on_text(parameters)
        elif command_type == "read_dialog":
            return self._read_and_respond_to_dialog(parameters)
        elif command_type == "monitor_changes":
            return self._monitor_screen_changes(parameters)
        else:
            return f"未知的OCR命令类型: {command_type}"
    
    def _extract_text_from_screen(self, parameters: Dict[str, Any]) -> str:
        """从屏幕或指定区域提取文本"""
        try:
            # 获取区域参数
            region = parameters.get("region")
            if region and isinstance(region, list) and len(region) == 4:
                region = tuple(region)
            else:
                region = None
            
            # 执行OCR
            result = self.ocr_processor.capture_screen_and_extract(region)
            
            if result["success"]:
                text = result["text"]
                if not text:
                    return "未从屏幕中提取到文本"
                # 限制返回文本长度
                if len(text) > 500:
                    text = text[:500] + "...（文本过长，已截断）"
                return f"从屏幕中提取的文本:\n\n{text}"
            else:
                return f"OCR处理失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"屏幕文本提取失败: {str(e)}")
            return f"提取屏幕文本时出错: {str(e)}"
    
    def _find_text_on_screen(self, parameters: Dict[str, Any]) -> str:
        """在屏幕上查找指定文本"""
        try:
            target_text = parameters.get("text", "")
            if not target_text:
                return "请提供要查找的文本"
            
            region = parameters.get("region")
            if region and isinstance(region, list) and len(region) == 4:
                region = tuple(region)
            else:
                region = None
            
            positions = self.ocr_processor.find_text_position(target_text, region)
            
            if not positions:
                return f"未在屏幕上找到文本 '{target_text}'"
            
            # 构建响应
            response = f"在屏幕上找到 {len(positions)} 个 '{target_text}' 的匹配项:\n"
            for i, pos in enumerate(positions, 1):
                left, top, right, bottom = pos["position"]
                response += f"\n{i}. 文本: '{pos['text']}'"
                response += f"\n   位置: 左上角({left},{top}) - 右下角({right},{bottom})"
                response += f"\n   置信度: {pos['confidence']}%"
            
            return response
        except Exception as e:
            logger.error(f"查找屏幕文本失败: {str(e)}")
            return f"查找屏幕文本时出错: {str(e)}"
    
    def _analyze_screen_content(self, parameters: Dict[str, Any]) -> str:
        """分析屏幕内容"""
        try:
            region = parameters.get("region")
            if region and isinstance(region, list) and len(region) == 4:
                region = tuple(region)
            else:
                region = None
            
            analysis = self.ocr_processor.analyze_screen_content(region)
            
            if analysis["success"]:
                response = "屏幕内容分析结果:\n\n"
                response += f"检测到 {analysis['line_count']} 行文本\n\n"
                
                if analysis['possible_titles']:
                    response += "可能的标题:\n"
                    for title in analysis['possible_titles']:
                        response += f"- {title}\n"
                    response += "\n"
                
                if analysis['possible_buttons']:
                    response += "可能的按钮:\n"
                    for button in analysis['possible_buttons']:
                        response += f"- {button}\n"
                
                # 提供一个简短的文本预览
                preview_text = analysis['text'][:200] + ("..." if len(analysis['text']) > 200 else "")
                response += f"\n文本预览:\n{preview_text}"
                
                return response
            else:
                return f"屏幕内容分析失败: {analysis.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"屏幕内容分析失败: {str(e)}")
            return f"分析屏幕内容时出错: {str(e)}"
    
    def _click_on_text(self, parameters: Dict[str, Any]) -> str:
        """点击屏幕上的指定文本"""
        try:
            target_text = parameters.get("text", "")
            if not target_text:
                return "请提供要点击的文本"
            
            wait_time = parameters.get("wait_time", 1.0)
            
            success = self.screen_manager.click_on_text(target_text, wait_time)
            
            if success:
                return f"已成功点击屏幕上的文本 '{target_text}'"
            else:
                return f"无法点击文本 '{target_text}'，可能未找到该文本或点击失败"
        except Exception as e:
            logger.error(f"点击屏幕文本失败: {str(e)}")
            return f"点击屏幕文本时出错: {str(e)}"
    
    def _read_and_respond_to_dialog(self, parameters: Dict[str, Any]) -> str:
        """读取并响应对话框"""
        try:
            wait_time = parameters.get("wait_time", 2.0)
            
            result = self.screen_manager.read_and_respond_to_dialog(wait_time)
            
            if result["success"]:
                response = f"检测到对话框类型: {result['dialog_type']}\n\n"
                response += f"对话框内容:\n{result['text']}\n\n"
                
                if result['suggested_action']:
                    response += f"建议操作: {result['suggested_action']}\n\n"
                
                if result['possible_buttons']:
                    response += "检测到的按钮:\n"
                    for button in result['possible_buttons']:
                        response += f"- {button}\n"
                
                return response
            else:
                return f"读取对话框失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"读取对话框失败: {str(e)}")
            return f"读取对话框时出错: {str(e)}"
    
    def _monitor_screen_changes(self, parameters: Dict[str, Any]) -> str:
        """监控屏幕文本变化"""
        try:
            baseline_text = parameters.get("baseline_text", "")
            timeout = parameters.get("timeout", 30)
            interval = parameters.get("interval", 2.0)
            
            # 如果未提供基线文本，则先获取当前屏幕文本作为基线
            if not baseline_text:
                current_result = self.ocr_processor.capture_screen_and_extract()
                if current_result["success"]:
                    baseline_text = current_result["text"]
                    logger.info("使用当前屏幕文本作为监控基线")
                else:
                    return f"获取基线文本失败: {current_result.get('error', '未知错误')}"
            
            response = f"开始监控屏幕变化，超时时间: {timeout}秒\n"
            response += f"基线文本预览: {baseline_text[:100]}{'...' if len(baseline_text) > 100 else ''}\n"
            response += "监控中...\n"
            
            # 在实际实现中，这可能需要在后台线程中运行
            # 这里我们返回一个提示，告知用户如何使用此功能
            response += "\n注意: 完整的监控功能需要在后台线程中运行，"
            response += "当前版本仅提供基础监控功能。"
            
            return response
        except Exception as e:
            logger.error(f"监控屏幕变化失败: {str(e)}")
            return f"监控屏幕变化时出错: {str(e)}"

class UtilityCommandHandler(CommandHandler):
    """实用工具命令处理器"""
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行实用工具相关命令"""
        command_type = parameters.get("type", "")
        
        if command_type == "calculate":
            return self._calculate(parameters)
        elif command_type == "set_reminder":
            return self._set_reminder(parameters)
        else:
            return f"未知的实用工具命令类型: {command_type}"
    
    def _calculate(self, parameters: Dict[str, Any]) -> str:
        """计算"""
        expression = parameters.get("expression", "")
        if not expression:
            return "请提供计算表达式"
        
        try:
            # 替换中文数学符号
            expr = expression.replace('加', '+').replace('减', '-')
            expr = expr.replace('乘', '*').replace('除', '/')
            
            # 安全计算
            import math
            # 使用一个安全的命名空间
            safe_dict = {
                '__builtins__': {},
                'math': math,
                'abs': abs,
                'round': round,
                'int': int,
                'float': float,
                'complex': complex
            }
            
            result = eval(expr, safe_dict)
            
            logger.info(f"计算结果: {expression} = {result}")
            return f"计算结果: {expression} = {result}"
        except ZeroDivisionError:
            return "错误: 除以零"
        except SyntaxError:
            return "错误: 表达式语法错误"
        except Exception as e:
            logger.error(f"计算失败: {str(e)}")
            return f"计算失败: {str(e)}"
    
    def _set_reminder(self, parameters: Dict[str, Any]) -> str:
        """设置提醒"""
        message = parameters.get("message", "")
        seconds = parameters.get("seconds", 0)
        
        if not message:
            return "请提供提醒消息"
        
        if seconds <= 0:
            return "请提供有效的提醒时间(秒)"
        
        try:
            import threading
            
            def reminder_task():
                time.sleep(seconds)
                print(f"\n🔔 提醒: {message}")
                # 尝试播放提示音
                try:
                    if self.current_os == "Windows":
                        import winsound
                        winsound.Beep(1000, 500)
                    elif self.current_os == "Darwin":  # macOS
                        subprocess.run(["afplay", "/System/Library/Sounds/Ping.aiff"])
                    else:  # Linux
                        subprocess.run(["aplay", "/usr/share/sounds/freedesktop/stereo/bell.oga"])
                except:
                    pass
            
            # 启动提醒线程
            thread = threading.Thread(target=reminder_task, daemon=True)
            thread.start()
            
            minutes = seconds // 60
            seconds_remainder = seconds % 60
            time_str = f"{minutes}分钟{seconds_remainder}秒" if minutes > 0 else f"{seconds}秒"
            
            logger.info(f"已设置提醒，将在{time_str}后提醒: {message}")
            return f"已设置提醒，将在{time_str}后提醒您: {message}"
        except Exception as e:
            logger.error(f"设置提醒失败: {str(e)}")
            return f"设置提醒失败: {str(e)}"

class ModelCommandHandler(CommandHandler):
    """大模型命令处理器"""
    
    def __init__(self, system_info: Dict[str, Any]):
        super().__init__(system_info)
        self.model_manager = None
        if MODEL_ENHANCER_AVAILABLE:
            try:
                self.model_manager = initialize_model_manager()
                logger.info("大模型管理器初始化成功")
            except Exception as e:
                logger.error(f"大模型管理器初始化失败: {str(e)}")
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行大模型相关命令"""
        if not MODEL_ENHANCER_AVAILABLE or not self.model_manager:
            return "大模型增强功能不可用，请确保已正确安装model_enhancer模块"
        
        command_type = parameters.get("type", "")
        
        if command_type == "generate":
            return self._generate_response(parameters)
        elif command_type == "set_active_model":
            return self._set_active_model(parameters)
        elif command_type == "get_model_info":
            return self._get_model_info(parameters)
        elif command_type == "reload_model":
            return self._reload_model(parameters)
        elif command_type == "run_evaluation":
            return self._run_evaluation()
        elif command_type == "process_command":
            return self._process_command(parameters)
        else:
            return f"未知的模型命令类型: {command_type}"
    
    def _generate_response(self, parameters: Dict[str, Any]) -> str:
        """生成模型响应"""
        try:
            prompt = parameters.get("prompt", "")
            if not prompt:
                return "请提供提示词"
            
            model_params = parameters.get("params", {})
            result = self.model_manager.generate(prompt, model_params)
            
            if result.get("success", False):
                response = result["response"]
                model_name = result.get("model", "未知模型")
                latency = result.get("latency", 0)
                
                return f"✅ 模型响应成功\n" \
                       f"📊 模型: {model_name} (延迟: {latency:.2f}秒)\n" \
                       f"📝 结果: {json.dumps(response, ensure_ascii=False, indent=2)}"
            else:
                return f"❌ 模型生成失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"生成响应失败: {str(e)}")
            return f"生成响应失败: {str(e)}"
    
    def _set_active_model(self, parameters: Dict[str, Any]) -> str:
        """设置活动模型"""
        try:
            model_name = parameters.get("model_name")
            if not model_name:
                return "请提供模型名称"
            
            success = self.model_manager.set_active_model(model_name)
            if success:
                return f"✅ 成功设置活动模型为: {model_name}"
            else:
                return f"❌ 模型 {model_name} 不存在或未加载"
        except Exception as e:
            logger.error(f"设置活动模型失败: {str(e)}")
            return f"设置活动模型失败: {str(e)}"
    
    def _get_model_info(self, parameters: Dict[str, Any]) -> str:
        """获取模型信息"""
        try:
            model_name = parameters.get("model_name")
            info = self.model_manager.get_model_info(model_name)
            
            if "error" in info:
                return f"❌ {info['error']}"
            
            # 格式化输出
            if model_name:
                # 单个模型信息
                return f"✅ 模型信息: {model_name}\n{json.dumps(info, ensure_ascii=False, indent=2)}"
            else:
                # 所有模型信息
                active = info.get("active_model", "")
                models = info.get("models", {})
                cache = info.get("cache_stats", {})
                
                response = f"✅ 活动模型: {active}\n"
                response += f"📊 已加载模型数量: {len(models)}\n\n"
                
                for name, model_info in models.items():
                    model_type = model_info.get("type", "")
                    initialized = model_info.get("initialized", False)
                    status = "✅ 已初始化" if initialized else "❌ 未初始化"
                    response += f"🔹 {name} ({model_type}) - {status}\n"
                
                response += f"\n💾 缓存统计: "
                response += f"大小: {cache.get('total_size', 0)}/"
                response += f"{cache.get('max_size', 0)}, "
                response += f"有效项: {cache.get('valid_entries', 0)}"
                
                return response
        except Exception as e:
            logger.error(f"获取模型信息失败: {str(e)}")
            return f"获取模型信息失败: {str(e)}"
    
    def _reload_model(self, parameters: Dict[str, Any]) -> str:
        """重新加载模型"""
        try:
            model_name = parameters.get("model_name")
            if not model_name:
                return "请提供模型名称"
            
            config = parameters.get("config")
            success = self.model_manager.reload_model(model_name, config)
            
            if success:
                return f"✅ 成功重新加载模型: {model_name}"
            else:
                return f"❌ 重新加载模型 {model_name} 失败"
        except Exception as e:
            logger.error(f"重新加载模型失败: {str(e)}")
            return f"重新加载模型失败: {str(e)}"
    
    def _run_evaluation(self) -> str:
        """运行模型评估"""
        try:
            results = self.model_manager.run_model_evaluation()
            
            if "error" in results:
                return f"❌ {results['error']}"
            
            response = "✅ 模型评估完成\n\n"
            
            # 按准确率排序
            sorted_results = sorted(
                results.items(),
                key=lambda x: x[1].get('accuracy', 0),
                reverse=True
            )
            
            for model_name, metrics in sorted_results:
                accuracy = metrics.get('accuracy', 0)
                latency = metrics.get('latency', 0)
                throughput = metrics.get('throughput', 0)
                
                response += f"🔹 {model_name}:\n"
                response += f"   🎯 准确率: {accuracy:.2%}\n"
                response += f"   ⏱️  延迟: {latency:.3f}秒\n"
                response += f"   📈 吞吐量: {throughput:.1f} 请求/秒\n"
            
            return response
        except Exception as e:
            logger.error(f"运行模型评估失败: {str(e)}")
            return f"运行模型评估失败: {str(e)}"
    
    def _process_command(self, parameters: Dict[str, Any]) -> str:
        """智能处理自然语言命令"""
        try:
            command_text = parameters.get("command", "")
            if not command_text:
                return "请提供命令文本"
            
            # 使用模型处理命令
            result = self.model_manager.generate(command_text, {
                "use_cache": True,
                "auto_select": True
            })
            
            if result.get('success', False):
                response = result['response']
                model_name = result.get('model', '未知模型')
                
                # 提取命令和参数
                command = response.get('command', 'unknown')
                confidence = response.get('confidence', 0)
                params = response.get('parameters', {})
                
                if confidence > 0.7:  # 高置信度才执行
                    return f"✅ 命令识别成功 (置信度: {confidence:.1%})\n" \
                           f"🔍 识别到命令: {command}\n" \
                           f"🤖 使用模型: {model_name}\n" \
                           f"⚙️  参数: {json.dumps(params, ensure_ascii=False)}"
                else:
                    return f"⚠️  命令识别置信度较低 ({confidence:.1%})\n" \
                           f"🔍 可能的命令: {command}\n" \
                           f"🤖 使用模型: {model_name}"
            else:
                return f"❌ 命令处理失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"处理命令失败: {str(e)}")
            return f"处理命令失败: {str(e)}"

class WorkflowCommandHandler(CommandHandler):
    """工作流命令处理器"""
    
    def __init__(self, system_info: Dict[str, Any]):
        super().__init__(system_info)
        self.workflow_manager = None
        if WORKFLOW_AVAILABLE:
            try:
                self.workflow_manager = WorkflowManager()
                logger.info("工作流管理器初始化成功")
            except Exception as e:
                logger.error(f"工作流管理器初始化失败: {str(e)}")
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行工作流相关命令"""
        if not WORKFLOW_AVAILABLE or not self.workflow_manager:
            return "工作流功能不可用，请确保已安装必要的依赖（pyautogui, keyboard）"
        
        command_type = parameters.get("type", "")
        
        if command_type == "start_recording":
            return self._start_recording(parameters)
        elif command_type == "stop_recording":
            return self._stop_recording(parameters)
        elif command_type == "play_workflow":
            return self._play_workflow(parameters)
        elif command_type == "list_workflows":
            return self._list_workflows()
        elif command_type == "save_workflow":
            return self._save_workflow(parameters)
        elif command_type == "delete_workflow":
            return self._delete_workflow(parameters)
        else:
            return f"未知的工作流命令类型: {command_type}"
    
    def _start_recording(self, parameters: Dict[str, Any]) -> str:
        """开始录制工作流"""
        try:
            hotkey = parameters.get("hotkey", "ctrl+alt+r")
            self.workflow_manager.start_recording(hotkey)
            logger.info(f"开始录制工作流，停止热键: {hotkey}")
            return f"开始录制工作流！请按 {hotkey} 停止录制"
        except Exception as e:
            logger.error(f"开始录制工作流失败: {str(e)}")
            return f"开始录制工作流失败: {str(e)}"
    
    def _stop_recording(self, parameters: Dict[str, Any]) -> str:
        """停止录制工作流"""
        try:
            result = self.workflow_manager.stop_recording()
            if result["success"]:
                action_count = len(result["actions"])
                logger.info(f"停止录制工作流，捕获了 {action_count} 个操作")
                return f"成功停止录制！已捕获 {action_count} 个操作"
            else:
                return f"停止录制失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"停止录制工作流失败: {str(e)}")
            return f"停止录制工作流失败: {str(e)}"
    
    def _play_workflow(self, parameters: Dict[str, Any]) -> str:
        """播放工作流"""
        try:
            workflow_name = parameters.get("name")
            if not workflow_name:
                return "请提供工作流名称"
            
            repeat_count = parameters.get("repeat", 1)
            delay = parameters.get("delay", 0)
            
            result = self.workflow_manager.play_workflow(workflow_name, repeat_count, delay)
            if result["success"]:
                logger.info(f"播放工作流成功: {workflow_name}")
                return f"成功播放工作流: {workflow_name}"
            else:
                return f"播放工作流失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"播放工作流失败: {str(e)}")
            return f"播放工作流失败: {str(e)}"
    
    def _list_workflows(self) -> str:
        """列出所有保存的工作流"""
        try:
            workflows = self.workflow_manager.list_workflows()
            
            if not workflows:
                return "没有找到保存的工作流"
            
            response = "已保存的工作流列表:\n"
            for i, workflow in enumerate(workflows, 1):
                response += f"\n{i}. {workflow['name']}"
                response += f"\n   操作数: {workflow['action_count']}"
                response += f"\n   创建时间: {workflow['created_at']}"
            
            logger.info(f"列出工作流成功，共 {len(workflows)} 个")
            return response
        except Exception as e:
            logger.error(f"列出工作流失败: {str(e)}")
            return f"列出工作流失败: {str(e)}"
    
    def _save_workflow(self, parameters: Dict[str, Any]) -> str:
        """保存当前录制的工作流"""
        try:
            workflow_name = parameters.get("name")
            if not workflow_name:
                return "请提供工作流名称"
            
            description = parameters.get("description", "")
            
            result = self.workflow_manager.save_workflow(workflow_name, description)
            if result["success"]:
                logger.info(f"保存工作流成功: {workflow_name}")
                return f"成功保存工作流: {workflow_name}"
            else:
                return f"保存工作流失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"保存工作流失败: {str(e)}")
            return f"保存工作流失败: {str(e)}"
    
    def _delete_workflow(self, parameters: Dict[str, Any]) -> str:
        """删除工作流"""
        try:
            workflow_name = parameters.get("name")
            if not workflow_name:
                return "请提供工作流名称"
            
            confirm = parameters.get("confirm", False)
            if not confirm:
                return "删除操作需要确认，请设置confirm=True"
            
            result = self.workflow_manager.delete_workflow(workflow_name)
            if result["success"]:
                logger.info(f"删除工作流成功: {workflow_name}")
                return f"成功删除工作流: {workflow_name}"
            else:
                return f"删除工作流失败: {result.get('error', '未知错误')}"
        except Exception as e:
            logger.error(f"删除工作流失败: {str(e)}")
            return f"删除工作流失败: {str(e)}"

class SystemController:
    """系统控制器，处理所有系统级操作"""
    
    def __init__(self):
        """初始化系统控制器"""
        # 收集系统信息
        self.system_info = {
            "os": platform.system(),
            "version": platform.version(),
            "architecture": platform.architecture(),
            "machine": platform.machine(),
            "node": platform.node()
        }
        
        # 初始化各种命令处理器
        self.command_handlers = {
            "application": ApplicationCommandHandler(self.system_info),
            "file": FileCommandHandler(self.system_info),
            "system": SystemCommandHandler(self.system_info),
            "media": MediaCommandHandler(self.system_info),
            "utility": UtilityCommandHandler(self.system_info),
            "ocr": OCRCommandHandler(self.system_info),
            "workflow": WorkflowCommandHandler(self.system_info),
            "model": ModelCommandHandler(self.system_info),
            "settings": SettingsCommandHandler(self.system_info)  # 新增设置命令处理器
        }
        
        # 用户ID
        self.current_user_id = "default"
        
        # 命令映射，用于兼容旧的命令格式
        self.command_mapping = {
            "open_application": ("application", {"type": "open"}),
            "close_application": ("application", {"type": "close"}),
            "close_window": ("application", {"type": "close_window"}),
            "get_system_info": ("system", {"type": "info"}),
            "list_files": ("file", {"type": "list"}),
            "search_files": ("file", {"type": "search"}),
            "create_folder": ("file", {"type": "create_folder"}),
            "edit_file": ("file", {"type": "edit"}),
            "copy_file": ("file", {"type": "copy"}),
            "move_file": ("file", {"type": "move"}),
            "delete_file": ("file", {"type": "delete"}),
            "control_volume": ("media", {}),  # volume命令需要特殊处理
            "control_brightness": ("media", {}),  # brightness命令需要特殊处理
            "shutdown": ("system", {"type": "shutdown"}),
            "restart": ("system", {"type": "restart"}),
            "sleep": ("system", {"type": "sleep"}),
            "screenshot": ("media", {"type": "screenshot"}),
            "play_music": ("media", {"type": "play_music"}),
            "calculate": ("utility", {"type": "calculate"}),
            "set_reminder": ("utility", {"type": "set_reminder"}),
            "extract_screen_text": ("ocr", {"type": "extract_text"}),
            "find_text_on_screen": ("ocr", {"type": "find_text"}),
            "analyze_screen": ("ocr", {"type": "analyze_screen"}),
            "click_text_on_screen": ("ocr", {"type": "click_text"}),
            "read_dialog": ("ocr", {"type": "read_dialog"}),
            "monitor_screen_changes": ("ocr", {"type": "monitor_changes"}),
            "monitor_system": ("system", {"type": "monitor"}),
            "start_workflow_recording": ("workflow", {"type": "start_recording"}),
            "stop_workflow_recording": ("workflow", {"type": "stop_recording"}),
            "play_workflow": ("workflow", {"type": "play_workflow"}),
            "list_workflows": ("workflow", {"type": "list_workflows"}),
            "save_workflow": ("workflow", {"type": "save_workflow"}),
            "delete_workflow": ("workflow", {"type": "delete_workflow"}),
            "process_command": ("model", {"type": "process_command"}),
            "get_model_info": ("model", {"type": "get_model_info"}),
            "set_active_model": ("model", {"type": "set_active_model"}),
            "run_model_evaluation": ("model", {"type": "run_evaluation"}),
            # 新增设置相关命令
            "get_settings": ("settings", {"type": "get_settings"}),
            "set_setting": ("settings", {"type": "set_setting"}),
            "reset_settings": ("settings", {"type": "reset_settings"}),
            "get_context": ("settings", {"type": "get_context"}),
            "clear_context": ("settings", {"type": "clear_context"})
        }
        
        logger.info(f"系统控制器初始化完成，当前操作系统: {self.system_info['os']}")
        
        # 初始化语音引擎
        self._init_voice_engine()
    
    def execute_command(self, command: str, parameters: Optional[Dict[str, Any]] = None) -> str:
        """执行系统命令
        
        Args:
            command: 命令名称
            parameters: 命令参数
            
        Returns:
            执行结果消息
        """
        if parameters is None:
            parameters = {}
        
        # 解析用户ID
        user_id = parameters.pop('user_id', self.current_user_id)
        self.current_user_id = user_id
        
        # 设置所有处理器的用户ID
        for handler in self.command_handlers.values():
            handler.set_user_id(user_id)
        
        # 记录命令到上下文
        if SETTINGS_AVAILABLE:
            add_to_context({
                "type": "command",
                "command": command,
                "parameters": parameters
            }, user_id)
        
        # 处理特殊的控制命令
        if command == "control_volume":
            action = parameters.get("action", "set")
            result = self.command_handlers["media"].execute({"type": action, **parameters})
        elif command == "control_brightness":
            action = parameters.get("action", "set")
            if action == "increase":
                result = self.command_handlers["media"].execute({"type": "brightness_up", **parameters})
            elif action == "decrease":
                result = self.command_handlers["media"].execute({"type": "brightness_down", **parameters})
            else:
                result = self.command_handlers["media"].execute({"type": action, **parameters})
        # 兼容旧的命令格式
        elif command in self.command_mapping:
            handler_type, base_params = self.command_mapping[command]
            # 合并参数
            merged_params = {**base_params, **parameters}
            
            if handler_type in self.command_handlers:
                result = self.command_handlers[handler_type].execute(merged_params)
            else:
                result = f"未知的处理器类型: {handler_type}"
        # 新的命令格式: type.subtype
        elif "." in command:
            try:
                handler_type, sub_type = command.split(".", 1)
                if handler_type in self.command_handlers:
                    params = {"type": sub_type, **parameters}
                    result = self.command_handlers[handler_type].execute(params)
                else:
                    result = f"未知的处理器类型: {handler_type}"
            except ValueError:
                result = f"命令格式错误: {command}"
        # 处理get_system_info的特殊情况
        elif command == "get_system_info":
            result = self.command_handlers["system"].execute({"type": "info"})
        else:
            logger.warning(f"未知命令: {command}")
            result = f"未知命令: {command}"
            # 尝试使用大模型解析自然语言命令
            if MODEL_ENHANCER_AVAILABLE and "model" in self.command_handlers:
                model_result = self.command_handlers["model"].execute({
                    "type": "process_command",
                    "command": command
                })
                result += f"\n\n💡 尝试解析为自然语言命令: {model_result}"
        
        # 记录结果到上下文
        if SETTINGS_AVAILABLE:
            add_to_context({
                "type": "response",
                "command": command,
                "result": result
            }, user_id)
        
        # 语音朗读结果
        self._speak_result(result)
        
        return result
    
    def _init_voice_engine(self):
        """初始化语音引擎"""
        try:
            import pyttsx3
            self.voice_engine = pyttsx3.init()
            voices = self.voice_engine.getProperty('voices')
            
            # 应用设置中的语音配置
            if SETTINGS_AVAILABLE:
                voice_settings = get_setting('voice', {})
                # 设置语音ID
                voice_id = voice_settings.get('voice_id', '')
                if voice_id:
                    for voice in voices:
                        if voice.id == voice_id:
                            self.voice_engine.setProperty('voice', voice.id)
                            break
                else:
                    # 尝试使用中文语音
                    for voice in voices:
                        if 'chinese' in voice.id.lower() or 'china' in voice.id.lower() or 'mandarin' in voice.id.lower():
                            self.voice_engine.setProperty('voice', voice.id)
                            break
                
                # 设置语音参数
                self.voice_engine.setProperty('rate', int(150 * voice_settings.get('rate', 1.0)))
                self.voice_engine.setProperty('volume', voice_settings.get('volume', 1.0))
            else:
                # 尝试使用中文语音
                for voice in voices:
                    if 'chinese' in voice.id.lower() or 'china' in voice.id.lower() or 'mandarin' in voice.id.lower():
                        self.voice_engine.setProperty('voice', voice.id)
                        break
                self.voice_engine.setProperty('rate', 150)
            
            logger.info("语音引擎初始化成功")
        except ImportError:
            self.voice_engine = None
            logger.warning("未找到pyttsx3库，语音功能将不可用")
        except Exception as e:
            self.voice_engine = None
            logger.error(f"语音引擎初始化失败: {str(e)}")
    
    def _speak_result(self, text: str):
        """语音朗读结果"""
        if self.voice_engine and SETTINGS_AVAILABLE and get_setting('voice.enabled', True):
            try:
                # 分析文本情绪
                emotion = "neutral"
                if any(keyword in text for keyword in ["成功", "✅", "完成", "好的"]):
                    emotion = "happy"
                elif any(keyword in text for keyword in ["错误", "失败", "❌", "无法"]):
                    emotion = "sad"
                elif any(keyword in text for keyword in ["警告", "⚠️", "注意"]):
                    emotion = "calm"
                
                # 应用情感参数
                voice_params = get_voice_params(emotion)
                self.voice_engine.setProperty('rate', int(150 * voice_params['rate']))
                self.voice_engine.setProperty('volume', voice_params['volume'])
                
                # 去除特殊字符，避免朗读问题
                clean_text = ''.join(c for c in text if c.isprintable() or c.isspace())
                
                # 异步朗读
                self.voice_engine.say(clean_text)
                self.voice_engine.runAndWait()
                
                # 添加静默间隔
                silence_duration = get_setting('voice.silence_duration', 0.2)
                time.sleep(silence_duration)
            except Exception as e:
                logger.error(f"语音朗读失败: {str(e)}")
    
    def get_available_commands(self) -> list:
        """获取所有可用命令
        
        Returns:
            可用命令列表
        """
        return list(self.command_mapping.keys())


class SettingsCommandHandler(CommandHandler):
    """设置命令处理器"""
    
    def __init__(self, system_info: Dict[str, Any]):
        super().__init__(system_info)
    
    def execute(self, parameters: Dict[str, Any]) -> str:
        """执行设置相关命令"""
        if not SETTINGS_AVAILABLE:
            return "设置管理功能不可用，请确保已正确安装settings_manager模块"
        
        command_type = parameters.get("type", "")
        
        if command_type == "get_settings":
            return self._get_settings(parameters)
        elif command_type == "set_setting":
            return self._set_setting(parameters)
        elif command_type == "reset_settings":
            return self._reset_settings()
        elif command_type == "get_context":
            return self._get_context()
        elif command_type == "clear_context":
            return self._clear_context()
        else:
            return f"未知的设置命令类型: {command_type}"
    
    def _get_settings(self, parameters: Dict[str, Any]) -> str:
        """获取设置"""
        try:
            key = parameters.get("key")
            
            if key:
                value = get_setting(key)
                if value is None:
                    return f"未找到设置项: {key}"
                return f"✅ 设置项 '{key}': {json.dumps(value, ensure_ascii=False, indent=2)}"
            else:
                # 获取所有设置
                all_settings = settings_manager.get_all_settings()
                return f"✅ 所有设置:\n{json.dumps(all_settings, ensure_ascii=False, indent=2)}"
        except Exception as e:
            return self._handle_error(e, "get_settings", parameters.get("_retry_count", 0))
    
    def _set_setting(self, parameters: Dict[str, Any]) -> str:
        """设置配置项"""
        try:
            key = parameters.get("key")
            value = parameters.get("value")
            
            if not key:
                return "请提供设置项的键名"
            
            # 类型转换
            if isinstance(value, str):
                # 尝试转换为基本类型
                if value.lower() == "true":
                    value = True
                elif value.lower() == "false":
                    value = False
                elif value.isdigit():
                    value = int(value)
                elif value.replace('.', '', 1).isdigit() and value.count('.') == 1:
                    value = float(value)
            
            success = set_setting(key, value)
            
            if success:
                # 特殊处理语音设置变更
                if key.startswith('voice.') and hasattr(SystemController, '_init_voice_engine'):
                    controller = SystemController()
                    controller._init_voice_engine()
                
                return f"✅ 成功设置 '{key}' = {json.dumps(value, ensure_ascii=False)}"
            else:
                return f"❌ 设置 '{key}' 失败"
        except Exception as e:
            return self._handle_error(e, "set_setting", parameters.get("_retry_count", 0))
    
    def _reset_settings(self) -> str:
        """重置所有设置"""
        try:
            success = settings_manager.reset_settings()
            if success:
                # 重置语音引擎
                if hasattr(SystemController, '_init_voice_engine'):
                    controller = SystemController()
                    controller._init_voice_engine()
                return "✅ 所有设置已重置为默认值"
            else:
                return "❌ 重置设置失败"
        except Exception as e:
            return self._handle_error(e, "reset_settings", parameters.get("_retry_count", 0))
    
    def _get_context(self) -> str:
        """获取当前上下文"""
        try:
            context = get_context(self.user_id)
            
            if not context:
                return "当前没有上下文历史"
            
            # 格式化上下文历史
            response = "✅ 上下文历史:\n"
            for i, item in enumerate(context, 1):
                item_type = item.get('type', 'unknown')
                timestamp = time.strftime('%Y-%m-%d %H:%M:%S', 
                                        time.localtime(item.get('timestamp', time.time())))
                
                response += f"\n{timestamp} [{item_type}]:\n"
                
                if item_type == 'command':
                    command = item.get('command', '')
                    params = item.get('parameters', {})
                    response += f"  命令: {command}\n"
                    response += f"  参数: {json.dumps(params, ensure_ascii=False)}"
                elif item_type == 'response':
                    result = item.get('result', '')
                    # 只显示前100个字符
                    if len(result) > 100:
                        result = result[:100] + "..."
                    response += f"  结果: {result}"
                elif item_type == 'error':
                    error = item.get('error', '')
                    command = item.get('command', '')
                    response += f"  命令: {command}\n"
                    response += f"  错误: {error}"
            
            return response
        except Exception as e:
            return self._handle_error(e, "get_context", parameters.get("_retry_count", 0))
    
    def _clear_context(self) -> str:
        """清除上下文"""
        try:
            clear_context(self.user_id)
            return "✅ 上下文历史已清除"
        except Exception as e:
            return self._handle_error(e, "clear_context", parameters.get("_retry_count", 0))